<template>
  <div class="add-warehouse-bg">
    <div class="back-btn-bar">
      <el-button class="back-btn" type="primary" link @click="goBackToHome">
        <el-icon>
          <ArrowLeft />
        </el-icon>
        返回无人机管理
      </el-button>
    </div>
    <div class="add-warehouse-page">
      <div class="page-header">
        <h2 class="page-title">新增无人机</h2>
        <p class="page-desc">
          请填写无人机的相关信息，带 <span class="required">*</span> 为必填项
        </p>
      </div>

      <el-form
        :model="form"
        label-width="120px"
        class="add-form"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="仓库选择" prop="warehouseId" class="form-item">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择仓库"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.warehouseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="无人机名称" prop="uavName" class="form-item">
          <el-input
            v-model="form.uavName"
            placeholder="请输入无人机名称"
            class="form-input"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="无人机型号" prop="uavType" class="form-item">
          <el-input
            v-model="form.uavType"
            placeholder="请输入无人机型号"
            class="form-input"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <!-- <el-form-item label="无人机外观" prop="uavExterior" class="form-item">
          <el-input v-model="form.uavExterior" type="textarea" placeholder="请描述无人机外观特征" class="form-textarea" :rows="3"
            maxlength="200" show-word-limit />
        </el-form-item> -->

        <!-- <el-form-item
          label="是否需要维护"
          prop="isMaintenance"
          class="form-item"
        >
          <el-radio-group v-model="form.isMaintenance">
            <el-radio value="1">是</el-radio>
            <el-radio value="0">否</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <!-- <el-form-item label="仓储位置" prop="storageLocation" class="form-item">
          <el-input
            v-model="form.storageLocation"
            placeholder="请输入仓储位置"
            class="form-input"
            maxlength="100"
            show-word-limit
          />
        </el-form-item> -->

        <!-- <el-form-item label="无人机状态" prop="uavStatus" class="form-item">
          <el-select
            v-model="form.uavStatus"
            placeholder="请选择无人机状态"
            style="width: 100%"
          >
            <el-option label="正常" value="0" />
            <el-option label="维修" value="1" />
          </el-select>
        </el-form-item> -->

        <el-form-item
          label="无人机图片"
          prop="file"
          class="form-item upload-item"
        >
          <el-upload
            class="upload-demo"
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
            :before-upload="beforeUpload"
          >
            <el-button type="primary" class="upload-btn">
              <el-icon>
                <Upload />
              </el-icon>
              选择图片
            </el-button>
          </el-upload>

          <div class="upload-preview" v-if="form.fileUrl">
            <img :src="form.fileUrl" class="preview-img" />
            <el-button link class="remove-img" @click="removeImage">
              <el-icon>
                <Delete />
              </el-icon>
              移除
            </el-button>
          </div>

          <p class="upload-tip">建议上传JPG、PNG格式的图片，大小不超过2MB</p>
        </el-form-item>

        <el-form-item class="form-actions">
          <el-button type="primary" @click="submit" class="submit-btn">
            <el-icon>
              <Check />
            </el-icon>
            提交
          </el-button>
          <el-button @click="goBack" class="cancel-btn">
            <el-icon>
              <ArrowLeft />
            </el-icon>
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { ArrowLeft, Upload, Delete, Check } from "@element-plus/icons-vue";

const router = useRouter();
const formRef = ref(null);

const form = reactive({
  warehouseId: "",
  uavName: "",
  uavType: "",
  uavExterior: "",
  isMaintenance: "0",
  storageLocation: "",
  uavStatus: "0",
  file: null,
  fileUrl: "",
});

const warehouseList = ref([]);

// 表单验证规则
const rules = {
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  uavName: [
    { required: true, message: "请输入无人机名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "无人机名称长度在2-50个字符之间",
      trigger: "blur",
    },
  ],
  uavType: [
    { required: true, message: "请输入无人机型号", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "无人机型号长度在2-50个字符之间",
      trigger: "blur",
    },
  ],
  uavExterior: [
    { required: true, message: "请输入无人机外观描述", trigger: "blur" },
    {
      min: 5,
      max: 200,
      message: "外观描述长度在5-200个字符之间",
      trigger: "blur",
    },
  ],
  isMaintenance: [
    { required: true, message: "请选择是否需要维护", trigger: "change" },
  ],
  storageLocation: [
    { required: true, message: "请输入仓储位置", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "仓储位置长度在2-100个字符之间",
      trigger: "blur",
    },
  ],
  uavStatus: [
    { required: true, message: "请选择无人机状态", trigger: "change" },
  ],
  file: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!form.file && !form.fileUrl) {
          callback(new Error("请上传无人机图片"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
};

// 获取仓库列表
const fetchWarehouseList = async () => {
  try {
    const res = await axios.get("/tielingpowergriduavservice/warehouse/list");
    if (res.data && res.data.code === 200) {
      warehouseList.value = res.data.data || [];
    } else {
      ElMessage.error("获取仓库列表失败：" + res.data.msg);
    }
  } catch (e) {
    ElMessage.error("请求异常：" + e.message);
  }
};

// 图片上传前校验
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJpgOrPng) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

const handleImageChange = (file) => {
  form.file = file.raw;
  form.fileUrl = URL.createObjectURL(file.raw);
};

const removeImage = () => {
  form.file = null;
  form.fileUrl = "";
};

const submit = async () => {
  // 表单验证
  await formRef.value.validate();

  const formData = new FormData();
  formData.append("warehouseId", form.warehouseId);
  formData.append("uavName", form.uavName);
  formData.append("uavType", form.uavType);
  formData.append("uavExterior", form.uavExterior);
  if (form.file) {
    formData.append("file", form.file);
  }

  try {
    const res = await axios.post(
      "/tielingpowergriduavservice/uav/add",
      formData
    );
    if (res.data.code === 200) {
      ElMessage.success("新增成功");
      router.push({ name: "DroneWarehouseHome", query: { tab: "drone-info" } });
    } else {
      ElMessage.error("新增失败：" + res.data.msg);
    }
  } catch (e) {
    ElMessage.error("请求异常：" + e.message);
  }
};

const goBack = () => {
  // 判断表单是否有修改
  if (
    form.warehouseId ||
    form.uavName ||
    form.uavType ||
    form.uavExterior ||
    form.file
  ) {
    ElMessageBox.confirm("当前表单内容未保存，确定要离开吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        router.push({
          name: "DroneWarehouseHome",
          query: { tab: "drone-info" },
        });
      })
      .catch(() => {
        // 取消离开
      });
  } else {
    router.push({ name: "DroneWarehouseHome", query: { tab: "drone-info" } });
  }
};

const goBackToHome = () => {
  router.push({ name: "DroneWarehouseHome", query: { tab: "drone-info" } });
};

onMounted(() => {
  fetchWarehouseList();
});
</script>

<style scoped>
.back-btn-bar {
  position: absolute;
  top: 38px;
  left: 60px;
  z-index: 10;
}

.back-btn {
  font-size: 16px;
  color: #3498db;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(52, 152, 219, 0.08);
  padding: 8px 22px;
  border: none;
  transition: background 0.2s;
}

.back-btn:hover {
  background: #eaf6fb;
  color: #217dbb;
}

.add-warehouse-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #e0f7fa 0%, #f8fafc 60%, #d1e9fc 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.add-warehouse-bg::before {
  content: "";
  position: absolute;
  left: -100px;
  top: 80px;
  width: 260px;
  height: 260px;
  background: radial-gradient(
    circle,
    #b2ebf2 0%,
    #e0f7fa 80%,
    transparent 100%
  );
  border-radius: 50%;
  z-index: 1;
  opacity: 0.5;
}

.add-warehouse-bg::after {
  content: "";
  position: absolute;
  right: -80px;
  bottom: 60px;
  width: 200px;
  height: 200px;
  background: radial-gradient(
    circle,
    #90caf9 0%,
    #d1e9fc 80%,
    transparent 100%
  );
  border-radius: 50%;
  z-index: 1;
  opacity: 0.4;
}

.add-warehouse-page {
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  padding: 38px 48px 32px 48px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(44, 62, 80, 0.13);
  position: relative;
  z-index: 2;
}

/* 页面头部 */
.page-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f1f5f9;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 20px;
  background-color: #3498db;
  margin-right: 10px;
  border-radius: 2px;
}

.page-desc {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.required {
  color: #e74c3c;
  font-weight: bold;
}

/* 表单样式 */
.add-form {
  width: 100%;
}

.form-item {
  margin-bottom: 25px;
  transition: all 0.3s;
}

.form-input {
  width: 100%;
  height: 42px;
  border-radius: 6px;
  border-color: #e2e8f0;
  transition: all 0.3s;
}

.form-input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.form-textarea {
  width: 100%;
  border-radius: 6px;
  border-color: #e2e8f0;
  resize: vertical;
}

/* 上传区域 */
.upload-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 15px;
}

.upload-btn {
  background-color: #3498db;
  border-color: #3498db;
  transition: all 0.3s;
}

.upload-btn:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}

.upload-preview {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-left: 120px;
  /* 与label宽度对齐 */
}

.preview-img {
  max-width: 200px;
  max-height: 120px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 4px;
  border: 1px solid #f1f5f9;
}

.remove-img {
  color: #e74c3c;
  padding: 5px 10px;
  height: auto;
}

.remove-img:hover {
  color: #c0392b;
  background-color: rgba(231, 76, 60, 0.05);
}

.upload-tip {
  font-size: 12px;
  color: #95a5a6;
  margin: 5px 0 0 120px;
  /* 与label宽度对齐 */
  line-height: 1.5;
}

/* 按钮区域 */
.form-actions {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #f1f5f9;
  display: flex;
  justify-content: flex-start;
  gap: 15px;
}

.submit-btn {
  background-color: #3498db;
  border-color: #3498db;
  padding: 8px 24px;
  font-size: 14px;
}

.submit-btn:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}

.cancel-btn {
  padding: 8px 24px;
  font-size: 14px;
  color: #7f8c8d;
  background-color: #f8fafc;
  border-color: #e2e8f0;
}

.cancel-btn:hover {
  background-color: #f1f5f9;
  color: #64748b;
  border-color: #cbd5e1;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .add-warehouse-page {
    margin: 15px;
    padding: 20px 15px;
  }

  .upload-preview,
  .upload-tip {
    margin-left: 100px;
  }

  .form-actions {
    flex-direction: column;
  }

  .submit-btn,
  .cancel-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .upload-preview,
  .upload-tip {
    margin-left: 80px;
  }

  .preview-img {
    max-width: 150px;
  }
}
</style>
